package com.onland.dfish.controller;

import com.alibaba.fastjson.JSONObject;
import com.onland.dfish.entity.Users;
import com.onland.dfish.entity.Videos;
import com.onland.dfish.service.IVideoService;
import com.onland.dfish.util.TimesUtils;
import com.sun.javafx.sg.prism.NGShape;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

@Controller
@RequestMapping("videos")
@Log4j2
public class VideoController {
    @Autowired
    private IVideoService videoService;
    @Autowired
    private ServletContext servletContext;
    /**
     * 视频上传目录
     */
    private String uploadDir;

    /**
     * 初始化方法,加载upload.properties
     */
    @PostConstruct
    public void init() {
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        uploadDir = rb.getString("video.upload.dir");
        String videoURLContext = rb.getString("video.url.context");
        log.info("视频上传目录:" + uploadDir);
        log.info("视频访问根目录:" + videoURLContext);
        servletContext.setAttribute("videoURLContext", videoURLContext);

    }

    /**
     * 观看历史
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("queryHistory")
    public String queryHistory(int userId, HttpServletRequest request) {
        List<Videos> videosList = videoService.queryHistory(userId);
        request.setAttribute("videosList", videosList);
        return "/user/watch_history.jsp";
    }

    @RequestMapping("queryUsers")
    public String queryUsers(int userId, HttpServletRequest request) {
        Users users = videoService.queryUsers(userId);
        request.setAttribute("users", users);
        return "/user/my_information.jsp";
    }

    /**
     * 根据Id删除视频
     *
     * @param id
     * @return
     */
    @GetMapping("delete")
    @ResponseBody
    public int deleteById(int id) {
        return videoService.deleteById(id);
    }

    /**
     * 上传视频
     *
     * @param videoFile
     * @param session
     * @return
     * @throws
     */
    @PostMapping(value = "/upload_video", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String fileVideo(MultipartFile videoFile, HttpSession session) throws Exception {
        //上传路径保存设置
        File dir = new File(uploadDir);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        Users user = (Users) session.getAttribute("users");
        //会员用户ID,未登录为0
        int userId = user != null ? user.getId() : 0;
        //原始视频文件名称
        String filename = videoFile.getOriginalFilename();
        //视频文件格式:U+用户ID+_+上传视频纳秒数
        String videoName = "U" + userId + "_" + TimesUtils.getMicTime() + filename.substring(filename.lastIndexOf('.'));
        videoFile.transferTo(new File(uploadDir + "/" + videoName));
        Map<Object, Object> hashMap = new HashMap<>();
        hashMap.put("code", 0);
        hashMap.put("msg", "上传成功");
        hashMap.put("videoName", videoName);
        return JSONObject.toJSONString(hashMap);

    }

    /**
     * 发布视频
     *
     * @param v
     * @return
     */
    @PostMapping("publish")
    public String publishVideo(Videos v, HttpSession session) {
        Users user = (Users) session.getAttribute("users");
        if (user != null) {
            int userId = user.getId();
            v.setUserId(userId);
        }
        int rows = videoService.createVideo(v);
        return "redirect:/user/pub_video_result.jsp?rows=" + rows;
    }

    /**
     * 根据视频分类查询
     *
     * @param supType 一级分类ID(必须)
     * @param subType 二级分类ID(可选)
     * @return
     */
    @GetMapping("find_type")
    public String findVideos(@RequestParam("sup_type") Integer supType, @RequestParam(value = "sub_type", required = false) Integer subType, Model model) {
        subType = subType == null ? 0 : subType;
        List<Videos> videosList = videoService.queryByType(supType, subType);
        model.addAttribute("videosList", videosList);
        return "/video/type.jsp";
    }

    /**
     * 根据关键字搜索
     *
     * @param kd
     * @param model
     * @return
     */
    @PostMapping("query_video")
    public String queryByKd(String kd, Model model) {
        List<Videos> videoList = videoService.queryByKd(kd);
        model.addAttribute("videoList", videoList);
        return "/video/sousuo.jsp";
    }

    @GetMapping("my_video")
    public String queryMyVideo(int userId,HttpServletRequest request){
        List<Videos> videosList=videoService.queryMyVideos(userId);
        request.setAttribute("videosList",videosList);
        return "/user/video_management.jsp";
    }

    /**
     * 播放视频
     * URL格式:http://localhost:8080/videos/1.html
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("{id}.html")
    public String playVideo(@PathVariable("id") int id, Model model) {
        Map<String, Object> videoMap = videoService.selectById(id);
        model.addAttribute("videoMap", videoMap);
        return "/video/play_video.jsp";
    }

    /**
     * 查询我的视频
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("queryVideos")
    public String queryVideos(int userId, HttpServletRequest request) {
        List<Videos> videosList = videoService.queryHistory(userId);
        request.setAttribute("videosList", videosList);
        return "/user/my_videos.jsp";
    }


    /**
     * 根据点赞次数，搜索热门视频
     *
     * @return
     */
    @GetMapping("hot")
    public String queryByLikeNum(Model model) {
        List<Map<String, Object>> hotList = videoService.queryByLikeNum();
        model.addAttribute("hotList", hotList);
        //设置状态 ,表示已加载数据
        model.addAttribute("loaded","true");
        return "/index.jsp";
    }

}